package filter

import (
	"regexp"
	"strings"

	"file_explorer/model"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/widget"
)

type FileNameFilter struct {
	entry *widget.Entry
}

func (filter *FileNameFilter) GetCanvasObject() fyne.CanvasObject {
	return filter.entry
}

func (filter *FileNameFilter) Filter(fileInfo *model.FileInfo) bool {
	if len(filter.entry.Text) == 0 {
		return true
	}

	filename := strings.ToLower(fileInfo.Name)
	keyword := strings.ToLower(filter.entry.Text)

	// 子串匹配
	if strings.Contains(filename, keyword) {
		return true
	}

	// 逆向匹配
	if strings.HasPrefix(keyword, "!") && !strings.Contains(filename, keyword) {
		return true
	}

	// 正则匹配
	match, _ := regexp.MatchString(keyword, filename)
	return match
}

func (filter *FileNameFilter) GetValue() string {
	return filter.entry.Text
}

func (filter *FileNameFilter) LoadValue(val string) {
	filter.entry.Text = val
	filter.entry.Refresh()
}

func (filter *FileNameFilter) Reset() {
	filter.LoadValue("")
}

func NewFileNameFilter(onChange func()) *FileNameFilter {
	filter := &FileNameFilter{
		entry: widget.NewEntry(),
	}

	filter.entry.PlaceHolder = "keyword"
	filter.entry.OnSubmitted = func(_ string) {
		onChange()
	}

	return filter
}
